-- curl -vv --fail -X DELETE -d "pday=20240714&param2=value2" http://localhost:8051/upload/user_panoramic_photo
-- curl -vv --fail -F "param1=value1" -F "pday=20240714" -F "file=@a.txt" localhost:8051/upload/user_panoramic_photo
local upload = require "resty.upload"
local cjson = require "cjson"

local base1 = "/oceanus-cv-share/"

local function create_directory(path)
    local command = "mkdir -p " .. path
    local handle = io.popen(command)
    local result = handle:read("*a")
    handle:close()
    return result
end

local function delete_directory(path)
    local command = "rm -rf " .. path
    local handle = io.popen(command)
    local result = handle:read("*a")
    handle:close()
    return result
end

local function get_last_segment(uri)
    local segments = {}
    
    for segment in uri:gmatch("([^/]+)") do
        table.insert(segments, segment)  
    end
    
    local last_segment = segments[#segments]
    if last_segment then
        last_segment = last_segment:gsub("/$", "")
    end
    
    return last_segment
end

local method = ngx.req.get_method()
local path = ngx.var.request_uri
local last_segment = get_last_segment(path)
local base_path = base1 .. last_segment .. "/"

if method == "DELETE" then
    ngx.req.read_body()
    local args = ngx.req.get_post_args()

    pday = args['pday']
    if not pday then
        ngx.status = ngx.HTTP_BAD_REQUEST
        ngx.say(cjson.encode({ success = false, error = "pass pday args to delete" }))
    end

    local match = ngx.re.match(pday, [[^\d{8}$]])
    if match then
        -- ngx.say("Valid date format: ", date_param)
        ngx.log(ngx.ERR, "delete dir: ", pday)
        delete_directory(base_path .. "/" .. pday .. "/")
    else
        ngx.status = ngx.HTTP_BAD_REQUEST
        ngx.say("Invalid date format: ", pday)
    end
    return
end


local chunk_size = 4*1024*1024
local form, err = upload:new(chunk_size)
if not form then
    ngx.status = ngx.HTTP_BAD_REQUEST
    ngx.say(cjson.encode({ success = false, error = err }))
    return
end



form:set_timeout(10000)

local file
local file_path
local params = {}
local current_param = nil
local filename = nil

while true do
    local typ, res, err = form:read()
    if not typ then
        ngx.status = ngx.HTTP_BAD_REQUEST
        ngx.say(cjson.encode({ success = false, error = err }))
        return
    end

    if typ == "header" then
        local name = res[1]
        local value = res[2]
        if name == "Content-Disposition" then
            local filename_r = ngx.re.match(value, 'filename="(.+)"')
            if filename_r then
                filename = filename_r[1]
                params["filename"] = filename
                current_param = "file"
            else
                current_param = ngx.re.match(value, 'name="(.+)"')[1]
            end
        end
    elseif typ == "body" then
        if current_param == "file" then
            pday = params["pday"]
            local match = ngx.re.match(pday, [[^\d{8}$]])
            if not match then
                ngx.status = ngx.HTTP_BAD_REQUEST
                ngx.say("Invalid date format: ", pday)
                return 
            end
            if not file then
                create_directory(base_path .. "/" .. pday .. "/")
                file_path = base_path .. "/" .. pday .. "/" .. filename
                file = io.open(file_path, "w+")
            end
            if not file then
                ngx.say("failed to open file ", file_path)
                return
            end
            file:write(res)
        else
            -- ngx.log(ngx.ERR, "Failed resss: ", res)
            params[current_param] = res
        end
    elseif typ == "part_end" then
        if file then
            file:close()
            file = nil
        end
        current_param = nil
    elseif typ == "eof" then
        break
    end
end

ngx.say(cjson.encode({ success = true, file_path = file_path, params = params }))
